package com.onlyyou.user.controller;

import com.alibaba.fastjson.JSON;
import com.onlyyou.user.VO.ResultVO;
import com.onlyyou.user.entity.User;
import com.onlyyou.user.enums.ResultEnum;
import com.onlyyou.user.exception.UserException;
import com.onlyyou.user.info.UserInfo;
import com.onlyyou.user.service.UserService;
import com.onlyyou.user.util.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jdk.nashorn.internal.objects.annotations.Getter;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: 小野
 * @Date: 2020/1/11 14:17
 */
@RestController
@Api(tags = "用户服务相关接口")
@RequestMapping("/")
@CrossOrigin
public class UserController {

    @Autowired
    private UserService userService;

    @ApiOperation(value = "获取数据行数")
    @GetMapping("/queryRows")
    public ResultVO queryRows() {
        return ResultUtil.success(userService.queryRows());
    }

    @ApiOperation(value = "获取用户登录状态")
    @GetMapping("/loginStatus")
    public ResultVO loginStatus(@RequestParam String userId){
        Long userid = JSON.parseObject(userId, Long.class);
        return ResultUtil.success(userService.findStatus(userid));
    }

    @ApiOperation(value = "普通用户登录")
    @PostMapping("/login")
    public Map<String, Object> login(String username, String password, HttpServletRequest httpServletRequest){
        Map<String, Object> resultMap = new HashMap<String, Object>();

        //1、取会员
        resultMap = userService.getUser(username, password);

        /*//2、如果没有取到会员，写入会员
        if (!(Boolean) resultMap.get("result")){
            resultMap = userService.insertUser(username, password);
        }*/

        //3、写入session
        HttpSession httpSession = httpServletRequest.getSession();
        String user = JSON.toJSONString(resultMap);
        httpSession.setAttribute("user", user);

        //4、返回信息
        return resultMap;
    }

    @ApiOperation(value = "注销",httpMethod = "GET")
    @GetMapping("/logout")
    public ResultVO logout(String username) {
        userService.logout(username);
        return ResultUtil.success();
    }

    @ApiOperation(value = "查询所有用户",httpMethod = "GET")
    @GetMapping("/findAll/{userId}")
    public Map<String,Object> findAll(@PathVariable("userId")Long userId, Integer page,Integer limit) {

        List<User> users = userService.findAll(userId,page-1, limit);
        Integer count=userService.queryRows();
        Map<String,Object> arrayMap=new HashMap<>();
        arrayMap.put("code",0);
        arrayMap.put("msg","ok");
        arrayMap.put("count",count);
        arrayMap.put("data",users);
        return arrayMap;
    }

    @ApiOperation(value = "查询所有用户",httpMethod = "GET")
    @GetMapping("/toLogin")
    public ResultVO toLogin() {
        //未登陆
        return ResultUtil.noLogin();
    }

    //后台登录
    @ApiOperation(value = "管理用户登录")
    @PostMapping("/adminLogin")
    public ResultVO adminLogin(String username, String password) {

        return ResultUtil.success(userService.adminLogin(username,password));
    }

    //登录
    @ApiOperation(value = "Get用户登录")
    @GetMapping("/login")
    public ResultVO login(String username, String password) {
        return ResultUtil.success( userService.login(username,password));

        /*//获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户信息
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        try {
            subject.login(token);
            return ResultVO.success(userService.findByName(username));
        } catch (UnknownAccountException e) {
            //用户不存在
            throw new UserException(ResultEnum.NULL);
        } catch (IncorrectCredentialsException e) {
            //密码错误
            throw new UserException(ResultEnum.PASSWORD_ERROR);
        }*/

    }

    @ApiOperation(value = "通过用户名获取用户状态")
    @GetMapping("/findByName")
    public ResultVO findByName(String username) {
        return ResultUtil.success(userService.findByName(username));
    }

    @ApiOperation(value = "新增用户")
    @PostMapping("/save")
    public ResultVO add(String username,String password,String phone,Integer permission) {
        UserInfo user=new UserInfo();
        user.setId(System.currentTimeMillis());
        user.setPassword(password);
        user.setPhone(phone);
        user.setUsername(username);
        user.setPermission(permission);
        user.setCreateTime(new Date());
        return ResultVO.success(userService.add(user));
    }

    @ApiOperation(value = "更新用户")
    @GetMapping("/update")
    public ResultVO update(User user) {
        return ResultVO.success(userService.update(user));
    }

    @GetMapping("/noAuth")
    public ResultVO noAuth() {
        return ResultUtil.unAuthorized();
    }
}
